<!--
  * 临期预警
  *
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-form class="query-form-wrapper smart-margin-bottom10 smart-radius-2" :model="queryForm" labelAlign="left">
    <a-row :gutter="[8, 10]">
      <a-col :span="4">
        <a-form-item label="商品名称" class="smart-margin-bottom0">
          <a-input v-model:value.trim="queryForm.keyword" placeholder="商品名称、助记码" allow-clear />
        </a-form-item>
      </a-col>
      <a-col :span="4">
        <a-form-item label="商品编码" class="smart-margin-bottom0">
          <a-input v-model:value.trim="queryForm.goods_no" placeholder="商品编码" allow-clear />
        </a-form-item>
      </a-col>
      <a-col :span="4">
        <a-button-group>
          <a-button type="primary" html-type="submit" @click="onSearch">
            <template #icon>
              <SearchOutlined />
            </template>
            查询
          </a-button>
          <a-button @click="resetQuery">
            <template #icon>
              <ReloadOutlined />
            </template>
            重置
          </a-button>
        </a-button-group>
      </a-col>
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->
  <div class="query-table-wrapper">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="openForm" type="primary" v-privilege="'goods:add'">
          <template #icon>
            <PlusOutlined />
          </template>
          新建
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.ERP.GOODS" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <div class="table-wrapper">
      <a-table
        size="small"
        :dataSource="tableData"
        :columns="columns"
        rowKey="id"
        bordered
        :scroll="{ x: 'max-content', y: tableScrollY }"
        :pagination="false"
        :showSorterTooltip="false"
        :loading="tableLoading"
        :row-selection="{
          selectedRowKeys: selectedRowKeyList,
          onChange: onSelectChange
        }"
        :showExpandColumn="false"
        expandRowByClick
      >
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'goods_name'">
            <CopyText :text="text">
              {{ text }}
            </CopyText>
          </template>
          <template v-if="column.dataIndex === 'batch_num'">
            <span>{{ record.batches.length }}</span>
          </template>
          <template v-if="column.dataIndex === 'deadline_warn_day'">
            <a-input-number v-model:value="record.deadline_warn_day" @blur="updateWarningTime(record)" addon-after="天" :min="1" :precision="0" />
          </template>
          <template v-if="column.dataIndex === 'action'">
            <div class="smart-table-operate">
              <a-button @click="deleteData(record.id, record.goods_name)" danger type="link" v-privilege="'dealer:del'">删除</a-button>
            </div>
          </template>
        </template>
      </a-table>
    </div>

    <div class="smart-query-table-page query-table-page">
      <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="() => `共${total}条`" />
    </div>
  </div>
  <ExpiredForm ref="ExpiredFormRef" />
</template>
<script lang="ts" setup>
import { message } from 'ant-design-vue'
import ExpiredForm from './components/expired-form.vue'
import { PAGE_SIZE_OPTIONS } from '@/constants/system/common-const'
import { TABLE_ID_CONST } from '@/constants/support/table-id-const'
import { WARNING_TYPE_ENUM } from '@/constants/business/storage/warning/warning-const'
import TableOperator from '@/components/support/table-operator/index.vue'
import { useQuery } from '@/hooks/web/use-query-hook'
import { warningRulesApi } from '@/api/business/storage/warehouse-api'
import { useResize } from '@/hooks/web/use-resize-hook'
// ----------------------------- 计算表格高度 -----------------------------
const { tableScrollY } = useResize()

// ---------------------------- 表格列 ----------------------------

const columns = reactive([
  {
    title: '商品名称',
    dataIndex: 'goods_name',
    width: 300
  },
  {
    title: '商品编码',
    dataIndex: 'no',
    width: 300
  },
  {
    title: '单位',
    dataIndex: 'unit_name'
  },
  {
    title: '批次数量',
    dataIndex: 'batch_count'
  },
  {
    title: '预警天数(天)',
    dataIndex: 'deadline_warn_day',
    width: 150
  },
  {
    title: '操作时间',
    dataIndex: 'operator_time'
  },
  {
    title: '操作员',
    dataIndex: 'operator'
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right'
  }
])

// ---------------------------- 查询数据表单和方法 ----------------------------
const { queryForm, tableData, tableLoading, total, resetQuery, onSearch, queryData, deleteData } = useQuery({
  fetchDataApi: async ({ page, limit, filter }) => {
    const params = {
      ...filter,
      page,
      limit,
      type: WARNING_TYPE_ENUM.EXPIRED.value
    }
    const res = await warningRulesApi.queryList(params)
    return {
      list: res.data?.data,
      total: res.data.total
    }
  },
  fetchDeleteApi: async (id) => {
    const res = await warningRulesApi.delete({ id, type: WARNING_TYPE_ENUM.EXPIRED.value })
    return !!res
  },
  queryFormFilter: {
    keyword: '',
    goods_no: ''
  },
  queryFormOp: {}
})
onMounted(queryData)

// 选择表格行
const selectedRowKeyList = ref<number[]>([])

function onSelectChange(selectedRowKeys: number[]) {
  selectedRowKeyList.value = selectedRowKeys
}

// 打开新建弹窗
const ExpiredFormRef = ref()
const openForm = () => {
  ExpiredFormRef.value.showDrawer()
}

// 更新预警天数
async function updateWarningTime(record) {
  try {
    const res = await warningRulesApi.update({
      id: record.id,
      type: WARNING_TYPE_ENUM.EXPIRED.value,
      value: record.deadline_warn_day
    })
    message.success(res.msg)
    onSearch()
  } catch (error) {
    message.error(error.msg)
  }
}
</script>
